<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>检测屏幕刷新率</title>
</head>

<body>
  <div>
    <h3 id='title'>当前屏幕刷新率为:</h3>
  </div>
  <script>
    const titleNode = document.querySelector('#title');
    let prev;
    // 展示代码
    const throttleShow = (() => {
      let prev = 0;
      return (interval) => {
        const now = Date.now()
        if (now - prev > 500) {
          const frame = (1000 / interval).toFixed(0);
          titleNode.innerHTML = `当前屏幕刷新率为(Hz):${frame}, 动画间隔为:${interval.toFixed(1)}ms`;
          prev = now
        }
      }
    })()
    // 使用performance.now()进行高精度计时
    const getNow = () => window.performance.now()
    // const getNow = () => Date.now()
    const calcFrame = () => {
      if (!prev) {
        prev = getNow()
      } else {
        const now = getNow()
        throttleShow(now - prev);
        prev = now;
      }
      requestAnimationFrame(calcFrame);
    }

    calcFrame();
  </script>
</body>

</html>